package com.wykj.business.service;

import com.wykj.business.dao.TuserDao;
import com.wykj.business.model.Tuser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/4/29.
 */
@Service
public class TuserService {
    @Autowired
    private TuserDao tuserDao;

    @PersistenceContext
    private EntityManager entityManager;

    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    public void savaOrUpdate(Tuser tuser){
        try{
            if(StringUtils.isEmpty(tuser.getId())){
                tuserDao.save(tuser);
            }else{
                tuserDao.saveAndFlush(tuser);
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    public void delete(Long id){
        try{
            tuserDao.delete(id);
        }catch(Exception e){
            e.printStackTrace();
        }
    }


    /**
     * 复杂查询测试
     * @param page
     * @param size
     * @return
     */
    public Page<Tuser> findByPage(int page, int size){

        PageRequest pageReq = this.buildPageRequest(page, size);
        Page<Tuser> tasks = this.tuserDao.findAll(new MySpec(), pageReq);
        return tasks;

    }

    /**
     * 建立分页排序请求
     * @param page
     * @param size
     * @return
     */
    private PageRequest buildPageRequest(int page, int size) {
        Sort sort = new Sort(Sort.Direction.DESC,"id");
        return new PageRequest(page,size, sort);
    }

    /**
     * 建立查询条件
     * @author liuxg
     * @date 2016年3月30日 下午2:04:39
     */
    private class MySpec implements Specification<Tuser>{

        @Override
        public Predicate toPredicate(Root<Tuser> root, CriteriaQuery<?> query, CriteriaBuilder cb) {

            //1.混合条件查询
          /*Path<String> exp1 = root.get("taskName");
            Path<Date>  exp2 = root.get("createTime");
            Path<String> exp3 = root.get("taskDetail");
            Predicate predicate = cb.and(cb.like(exp1, "%taskName%"),cb.lessThan(exp2, new Date()));
            return cb.or(predicate,cb.equal(exp3, "kkk"));

            类似的sql语句为:
            Hibernate:
                select
                    count(task0_.id) as col_0_0_
                from
                    tb_task task0_
                where
                    (
                        task0_.task_name like ?
                    )
                    and task0_.create_time<?
                    or task0_.task_detail=?
            */

            //2.多表查询
        /*Join<Task,Project> join = root.join("project", JoinType.INNER);
            Path<String> exp4 = join.get("projectName");
            return cb.like(exp4, "%projectName%");

            Hibernate:
            select
                count(task0_.id) as col_0_0_
            from
                tb_task task0_
            inner join
                tb_project project1_
                    on task0_.project_id=project1_.id
            where
                project1_.project_name like ?*/
            return null ;
        }
    }



    public Page<Tuser> findTuserByPage(Pageable pageable, Integer isEnabled) {

        //CriteriaBuilder,用来构建CritiaQuery的构建器对象
        CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();

        //CriteriaQuery,它包含着查询语句的条件各个部分，比如：select 、from、where、group by、order by等
        CriteriaQuery<Tuser> criteriaQuery = criteriaBuilder.createQuery(Tuser.class);

        //查询根，用于获取查询实例的属性，通过CriteriaQuery的from方法获取
        Root<Tuser> rootFrom = criteriaQuery.from(Tuser.class);

        //查询条件
        List<Predicate> predicates = new ArrayList<Predicate>();

        if (null != isEnabled) {
            Predicate predicate = criteriaBuilder.equal(rootFrom.get("isEnabled").as(Integer.class), isEnabled);
            predicates.add(predicate);
        }
        //格式化参数
        criteriaQuery.where(criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()])));

        //默认按照id排序（从小到大）
        criteriaQuery.orderBy(criteriaBuilder.asc(rootFrom.get("id")));

        //SQL查询对象
        TypedQuery<Tuser> createQuery = entityManager.createQuery(criteriaQuery);

        //分页参数
        Integer pageSize = pageable.getPageSize();
        Integer pageNo = pageable.getPageNumber();

        //计数查询结果条数
        TypedQuery<Tuser> createCountQuery = entityManager.createQuery(criteriaQuery);

        // 实际查询返回分页对象
        int startIndex = pageSize * pageNo;
        createQuery.setFirstResult(startIndex);
        createQuery.setMaxResults(pageable.getPageSize());
        Page<Tuser> pageRst =
                new PageImpl<Tuser>(createQuery.getResultList(), pageable, createCountQuery.getResultList().size());
        return pageRst;

    }

    //制造查询条件结果(建议存放map)
    private Specification<Tuser> getWhereClause(final Integer isEnabled) {
        return new Specification<Tuser>() {
            public Predicate toPredicate(Root<Tuser> r, CriteriaQuery<?> q, CriteriaBuilder cb) {
                Predicate predicate = cb.conjunction();
                if (null != isEnabled) {
                    predicate = cb.equal(r.get("isEnabled").as(Integer.class), isEnabled);
                }
                return predicate;
            }
        };
    }

}
